package blue.web.dao.service;

import blue.commons.enums.UserTypeEnum;
import blue.erp.model.*;
import blue.tools.constants.BlueContants;
import blue.dao.base.BaseMapper;
import blue.erp.dao.BlueClassMapper;
import blue.splitclass.model.ElectiveTask;
import blue.tools.commons.BlueStringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;

@Service
public class BlueClassService extends BaseService {

    @Autowired
    private BlueClassMapper blueClassMapper;

    @Autowired
    private BlueGradeService blueGradeService;

    @Autowired
    private ElectiveTaskService electiveTaskService;

    @Autowired
    private SysUserService sysUserService;

    public int deleteBatch(String ids,Long schoolId) {

        List idList= BlueStringUtils.convertString2Num(ids,",");
        BlueClassExample example=new BlueClassExample();
        example.createCriteria().andIdIn(idList);
        clearCache(schoolId);
        return blueClassMapper.deleteByExample(example);
    }


    public int save(BlueClass record) {

        if(record==null || StringUtils.isBlank(record.getName())){
            return 0;
        }

        BlueClassExample example=new BlueClassExample();
        BlueClassExample.Criteria criteria=example.createCriteria().andNameEqualTo(record.getName()).andGradeidEqualTo(record.getGradeid());

        if(record.getId()!=null){
            criteria.andIdEqualTo(record.getId());
        }else {
            if(record.getHeadTeacherid()!=null){
                Object sysUser=sysUserService.selectByPrimaryKey(record.getHeadTeacherid(),record.getSchoolid());
                if(sysUser!=null){
                    record.setHeadTeacherName(((SysUser)sysUser).getRealName());
                }
            }

            if(record.getSquadLeaderid()!=null){
                Object sysUser=sysUserService.selectByPrimaryKey(record.getSquadLeaderid(),record.getSchoolid());
                if(sysUser!=null){
                    record.setSquadLeaderName(((SysUser)sysUser).getRealName());
                }
            }
        }

        return this.baseSave(record,example);

    }


    public  List<BlueClass> selectByBlueClass(BlueClass blueClass,List<Long> gradeIds,boolean directFormDb) {

        if(blueClass.getSchoolid()==null || CollectionUtils.isEmpty(gradeIds)){
            return null;
        }

        gradeIds.sort((h1,h2)-> (int) (h1-h2));

        Object cacheObject=redisService.getValue(BlueContants.prefix_className_GradeList_+blueClass.getSchoolid()+blueClass.getName()+StringUtils.join(gradeIds,"-"));
        if(!directFormDb && cacheObject!=null){
            return JSONArray.parseArray(cacheObject.toString(),BlueClass.class);
        }else {

            BlueClassExample example=new BlueClassExample();
            BlueClassExample.Criteria criteria=example.createCriteria().andSchoolidEqualTo(blueClass.getSchoolid());

            if(CollectionUtils.isNotEmpty(gradeIds)){
                criteria.andGradeidIn(gradeIds);
            }

            if(StringUtils.isNotBlank(blueClass.getName())){
                criteria.andNameLike("%"+blueClass.getName()+"%");
            }

            List<BlueClass> blueClassList=selectByExample(example,true);


            if(CollectionUtils.isNotEmpty(blueClassList)){
                redisService.setValue(BlueContants.prefix_className_GradeList_+blueClass.getSchoolid()+blueClass.getName()+StringUtils.join(gradeIds,"-")+blueClass.getSchoolid(),JSONArray.toJSONString(blueClassList));
            }

            return blueClassList;
        }
    }

    //异步check数据信息
    @Async
    public void sanClassTable() {
        int pageSize = 200;
        PageHelper.startPage(0, pageSize);
        BlueClassExample example = new BlueClassExample();
        BlueClassExample.Criteria criteria = example.createCriteria();
        List<BlueClass> blueClassList = this.getBaseMapper().selectByExample(example);
        addClassInfo(blueClassList);
        PageInfo pageInfo = new PageInfo(blueClassList);
        for (int i = 1; i < pageInfo.getPages(); i++) {
            PageHelper.startPage(i, pageSize);
            example = new BlueClassExample();
            criteria = example.createCriteria();
            addClassInfo(this.getBaseMapper().selectByExample(example));
        }
    }


    public void addClassInfo(List<BlueClass> blueClassList){
        for(BlueClass blueClass:blueClassList){
            //查询总人数
            SysUserExample example=new SysUserExample();
            SysUserExample.Criteria criteria=example.createCriteria().andClassIdsRegexp(blueClass.getId().toString());
            List totalList=sysUserService.select(example);
            boolean isGroup=false;
            if(CollectionUtils.isEmpty(totalList)){
                example=new SysUserExample();
                criteria=example.createCriteria().andGroupIdsRegexp(blueClass.getId().toString());
                totalList=sysUserService.select(example);
                isGroup=true;
            }

            if(CollectionUtils.isEmpty(totalList)){
                continue;
            }

            blueClass.setStudentCount(totalList.size());

            //获取男生数量
            example=new SysUserExample();
            criteria=example.createCriteria();
            if(isGroup){
                criteria.andGroupIdsRegexp(blueClass.getId().toString());
            }else {
                criteria.andClassIdsRegexp(blueClass.getId().toString());
            }
            criteria.andSexEqualTo("男");
            List manList=sysUserService.select(example);
            blueClass.setManCount(manList.size());
            blueClass.setFemanCount(blueClass.getStudentCount()-blueClass.getManCount());

            this.save(blueClass);
        }
    }

    public  List<BlueClass> selectClassByGradeId(Long gradeId,Long schoolId,boolean directFormDb) {

        if(gradeId==null || schoolId==null){
            return null;
        }

        BlueClass blueClass=new BlueClass();
        blueClass.setSchoolid(schoolId);

        List<Long> gradeIds=new LinkedList<>();
        gradeIds.add(gradeId);

        return selectByBlueClass(blueClass,gradeIds,directFormDb);
    }
    //根据分班的任务id查询数据
    public  List<BlueClass> selectClassBySplitTask(Long taskId,Long schoolId) {

        if(taskId==null || schoolId==null){
            return null;
        }
        ElectiveTask electiveTask=electiveTaskService.selectById(taskId,schoolId);
        if(electiveTask==null||electiveTask.getGradeid()==null){
            return null;
        }

        return selectClassByGradeId(electiveTask.getGradeid(),electiveTask.getSchoolid(),false);
    }


    public BlueClass selectByPrimaryKey(Long id,Long schoolId,boolean flush){

        Object gradeCache=this.baseSelectByPrimaryKey(id,BlueContants.prefix_classId,schoolId,flush);

        if(gradeCache!=null){
            return JSONObject.parseObject(gradeCache.toString(),BlueClass.class);
        }

        return null;
    }


    public List<BlueClass> selectByExample(BlueClassExample example, boolean isShowGradeName){
        List<BlueClass> blueClassList=this.getBaseMapper().selectByExample(example);

        if(isShowGradeName && CollectionUtils.isNotEmpty(blueClassList)){
            for(BlueClass blueClass:blueClassList){

                if(blueClass.getGradeid()==null){
                    continue;
                }

                BlueGrade blueGrade=blueGradeService.selectByPrimaryKey(blueClass.getGradeid(),blueClass.getSchoolid(),true);
                if(blueGrade!=null){
                    blueClass.setGradeName(blueGrade.getName());
                }
            }
        }

        return blueClassList;
    }



    @Override
    public BaseMapper getBaseMapper() {
        return this.blueClassMapper;
    }

    @Override
    public void clearCache(Long schoolId,Object... extend) {
        redisService.vagueDelete(BlueContants.prefix_className_GradeList_+schoolId);
    }
}
